package com.xjrsoft.module.workflow.listener;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xjrsoft.core.tool.utils.*;
import com.xjrsoft.module.base.entity.XjrBaseRole;
import com.xjrsoft.module.base.entity.XjrBaseTempfield;
import com.xjrsoft.module.base.entity.XjrBaseUser;
import com.xjrsoft.module.base.service.IXjrBaseRoleService;
import com.xjrsoft.module.base.service.IXjrBaseTempfieldService;
import com.xjrsoft.module.base.service.IXjrBaseUserRelationService;
import com.xjrsoft.module.workflow.entity.XjrNwfScheme;
import com.xjrsoft.module.workflow.service.IXjrNwfSchemeService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


//流程任务创建监听
@Slf4j
@Component
public class TaskExecutionListener implements TaskListener {

    @SneakyThrows
    @Override
    public void notify(DelegateTask delegateTask) {
        //设置审批人
        IXjrBaseTempfieldService xjrBaseTempfieldService=SpringUtil.getBean(IXjrBaseTempfieldService.class);
        IXjrNwfSchemeService nwfSchemeService=SpringUtil.getBean(IXjrNwfSchemeService.class);
        HistoryService historyService=SpringUtil.getBean(HistoryService.class);
        TaskService taskService = SpringUtil.getBean(TaskService.class);
        RuntimeService runtimeService= SpringUtil.getBean(RuntimeService.class);
        IXjrBaseRoleService roleService=SpringUtil.getBean(IXjrBaseRoleService.class);
        IXjrBaseUserRelationService userRelationService = SpringUtil.getBean(IXjrBaseUserRelationService.class);
        RepositoryService repositoryService=SpringUtil.getBean(RepositoryService.class);
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(delegateTask.getProcessDefinitionId()).singleResult();
        List<HistoricActivityInstance> histList = historyService.createHistoricActivityInstanceQuery().processInstanceId(delegateTask.getProcessInstanceId()).orderByHistoricActivityInstanceStartTime().asc().list();
        String version = String.valueOf(processDefinition.getVersion());
        String nwfSchemeInfoId = String.valueOf(processDefinition.getDescription());
        XjrNwfScheme xjrNwfScheme = nwfSchemeService.getBySchemeInfoId(nwfSchemeInfoId);
        if (xjrNwfScheme != null) {
            String fjson = xjrNwfScheme.getFjson();
            String key = xjrNwfScheme.getSchemeInfoId() + StringPool.UNDERSCORE + delegateTask.getTaskDefinitionKey() + StringPool.UNDERSCORE + version;
            JSONObject jsonObject = JSONObject.parseObject(fjson);
            Boolean fassign = jsonObject.getJSONObject("properties").getBoolean("F_Assign");
            XjrBaseTempfield xjrBaseTempfield = xjrBaseTempfieldService.getByIdAndType(key, "1");
            //是否会签
            if (xjrBaseTempfield == null) {
                if (!fassign) {
                    // 查询keyvalue表
                    XjrBaseTempfield baseTempfield = xjrBaseTempfieldService.getByIdAndType(key, "4");
                    JSONArray userArray = new JSONArray();
                    if (baseTempfield != null) {
                        userArray = JSONObject.parseArray(baseTempfield.getFvalue());
                    }
                    //全部候选人
                    Set<String> assigns = FlowableUtil.checkUsers(delegateTask.getProcessInstanceId(), histList, userArray);
                    if (CollectionUtil.isEmpty(assigns)) {
                        // 无对应处理人,是否由上一节点指定
                        Integer fHandle = jsonObject.getJSONObject("properties").getInteger("F_Handle");
                        if (fHandle!=null&&fHandle == 1) {
                            XjrBaseRole sysRole = roleService.getSysRole();
                            List<XjrBaseUser> usersOfObject = userRelationService.getUsersOfObject(sysRole.getRoleId(), 1);
                            List<String> userIds = usersOfObject.stream().map(s -> s.getUserId()).collect(Collectors.toList());
                            for (String userId : userIds) {
                                taskService.addCandidateUser(delegateTask.getId(), userId);
                            }
                        }
                    } else {
                        //添加动态候选人
                        for (String userId : assigns) {
                            taskService.addCandidateUser(delegateTask.getId(), userId);
                        }
                    }
                }
            } else if (StringUtil.equals(delegateTask.getAssignee(), "xxx")) {
                Integer fHandle = JSONObject.parseObject(xjrNwfScheme.getFjson()).getJSONObject("properties").getInteger("F_Handle");
                JSONArray userArrays = new JSONArray();
                //如果是会签
                if (xjrBaseTempfield != null) {
                    String fvalue = xjrBaseTempfield.getFvalue();
                    if (StringUtil.isNotBlank(fvalue)) {
                        JSONObject parseObject = JSONObject.parseObject(fvalue);
                        JSONArray users = parseObject.getJSONArray("users");
                        Set<String> userSet = FlowableUtil.checkUsers(delegateTask.getProcessInstanceId(), histList, users);
                        userArrays = new JSONArray(new ArrayList<>(userSet));
                    }
                }
                if (CollectionUtil.isEmpty(userArrays)) {
                    // 获取无对应处理人的配置
                    if (fHandle != null && fHandle == 1) {
                        // 添加超级管理员下的人员为候选人
                        XjrBaseRole sysRole = roleService.getSysRole();
                        List<XjrBaseUser> usersOfObject = userRelationService.getUsersOfObject(sysRole.getRoleId(), 1);
                        for (XjrBaseUser xjrBaseUser : usersOfObject) {
                            userArrays.add(xjrBaseUser.getUserId());
                        }
                    }
                }
                runtimeService.setVariable(delegateTask.getExecutionId(), delegateTask.getTaskDefinitionKey()+StringPool.UNDERSCORE+"usernamelist", userArrays);
                runtimeService.setVariable(delegateTask.getExecutionId(), delegateTask.getTaskDefinitionKey()+StringPool.UNDERSCORE+"count", userArrays.size());
                // 减签
                runtimeService.deleteMultiInstanceExecution(delegateTask.getExecutionId(), false);
                for (int i = 0; i < userArrays.size(); i++) {
                    JSONObject map = new JSONObject();
                    map.put("username", userArrays.getString(i));
                    runtimeService.addMultiInstanceExecution(delegateTask.getTaskDefinitionKey(), delegateTask.getProcessInstanceId(), map);
                }
            }
        }
    }
}
